package cn.xuchunh.campusbbs.ui.fragments;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.android.volley.Response;
import com.android.volley.VolleyError;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.xuchunh.campusbbs.AppContext;
import cn.xuchunh.campusbbs.R;
import cn.xuchunh.campusbbs.adapter.ReplyListAdapter2;
import cn.xuchunh.campusbbs.api.ApiConstant;
import cn.xuchunh.campusbbs.base.BaseRecyclerViewAdapter;
import cn.xuchunh.campusbbs.bean.OperateResult;
import cn.xuchunh.campusbbs.net.XJsonListener;
import cn.xuchunh.campusbbs.storage.sqlite.DBManager;
import cn.xuchunh.campusbbs.ui.activities.TopicDetailActivity;
import cn.xuchunh.campusbbs.adapter.ReplyListAdapter;
import cn.xuchunh.campusbbs.base.BaseRefreshListFragment;
import cn.xuchunh.campusbbs.bean.Reply;
import cn.xuchunh.campusbbs.bean.ReplyContent;
import cn.xuchunh.campusbbs.bean.Topic;
import cn.xuchunh.campusbbs.net.HttpRequestManager;
import cn.xuchunh.campusbbs.utils.IntentParamsKey;
import cn.xuchunh.campusbbs.utils.JsonKey;
import cn.xuchunh.campusbbs.utils.JsonParser;
import cn.xuchunh.campusbbs.viewholder.TopicReplyViewHolder;
import cn.xuchunh.campusbbs.widget.DividerItemDecoration;
import cn.xuchunh.campusbbs.widget.LoadingLayout;

/**
 * Created by XuChunH on 2015/9/14.
 */
public class TopicReplyListlFragment extends BaseRefreshListFragment<TopicReplyViewHolder, Reply> {

    public static final String TAG = TopicReplyListlFragment.class.getSimpleName();

    private Topic topic;

    public static TopicReplyListlFragment getInstance(Topic topic) {
        TopicReplyListlFragment topicDetailFragment = new TopicReplyListlFragment();
        Bundle args = new Bundle();
        args.putSerializable(IntentParamsKey.TOPIC, topic);
        topicDetailFragment.setArguments(args);
        return topicDetailFragment;
    }

    public TopicReplyListlFragment() {
    }

    @Override
    protected void beforeInitView() {
        super.beforeInitView();
        setHasOptionsMenu(true);
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        getRecyclerView().addItemDecoration(
                new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_topic, menu);
        MenuItem menuItem = menu.findItem(R.id.collect);
        menuItem.setTitle(topic.isFavor() ? "取消收藏" : "收藏");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (getLoadingLayout().getState() == LoadingLayout.STATE_SHOW_COTNENT) {
            int id = item.getItemId();
            if (id == R.id.share) {
                share();
                return true;
            } else if (id == R.id.collect) {
                favotite();
                return true;
            } else if (id == R.id.copy_link) {
                copyLink();
                return true;
            } else if (id == R.id.browser) {
                browser();
                return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    private void share() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        PackageManager packageManager = getActivity().getPackageManager();
        List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
        if (activities.size() > 0) {
            intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
            intent.putExtra(Intent.EXTRA_TEXT, topic.getSourceWebUrl());
            intent.putExtra(Intent.EXTRA_TITLE, topic.getTitle());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

    private void copyLink() {
        ClipboardManager clipboardManager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText("text", topic.getSourceWebUrl());
        clipboardManager.setPrimaryClip(clipData);
        showToast("链接已复制");
    }

    private void browser() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(topic.getSourceWebUrl()));
        PackageManager packageManager = getActivity().getPackageManager();
        List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
        boolean isIntentSafe = activities.size() > 0;
        if (isIntentSafe) {
            startActivity(intent);
        }
    }

    private void favotite() {
        HttpRequestManager.getInstance(getActivity()).favorite(topic.getId(),
                topic.isFavor() ? ApiConstant.ACTION_DELFAVORITE : ApiConstant.ACTION_FAVORITE,
                favoriteListener,
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        favoriteFail();
                        Log.e(TAG, error.getMessage());
                    }
                },
                "favorite");
    }

    XJsonListener<OperateResult> favoriteListener = new XJsonListener<OperateResult>() {
        @Override
        public OperateResult parseJson(String json) throws Exception {
            JSONObject jsonObject = new JSONObject(json);
            OperateResult result = new OperateResult();
            result.setSuccess(jsonObject.optInt(JsonKey.RS) == 1);
            result.setMessage(jsonObject.optString(JsonKey.ERRCODE));
            return result;
        }

        @Override
        public void onResponse(OperateResult response) {
            if (response.isSuccess()) {
                showToast(topic.isFavor() ? R.string.succeed_delfavorite : R.string.succeed_favorite);
                topic.setFavor(!topic.isFavor());
                getActivity().invalidateOptionsMenu();
            }else {
                favoriteFail();
            }
        }
    };

    private void favoriteFail() {
        showToast(topic.isFavor() ? R.string.error_delfavorite : R.string.error_favorite);
    }

    @Override
    protected RecyclerView.LayoutManager createLayoutManager() {
        return new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
    }

    @Override
    protected BaseRecyclerViewAdapter<TopicReplyViewHolder, Reply> createAdapter() {
        return new ReplyListAdapter2(getActivity(), topic);
    }

    @Override
    protected List<Reply> parse(JSONObject jsonObject) throws JSONException {
        List<Reply> replyList = new ArrayList<>();
        if (getPage() == 1) {
            JSONObject topicJson = jsonObject.optJSONObject(JsonKey.TOPIC);
            topic.setTitle(topicJson.optString(JsonKey.TITLE));
            topic.setSortId(topicJson.optInt(JsonKey.SORTID));
            topic.setReplies(topicJson.optInt(JsonKey.REPLIES));
            topic.setHits(topicJson.optInt(JsonKey.HITS));
            topic.setEssence(topicJson.optInt(JsonKey.ESSENCE) != 0);
            topic.setVote(topicJson.optInt(JsonKey.VOTE));
            topic.setHot(topicJson.optInt(JsonKey.HOT) != 0);
            topic.setTop(topicJson.optInt(JsonKey.TOP) != 0);
            topic.setFavor(topicJson.optInt(JsonKey.IS_FAVOR) == 1);
            String createDate = topicJson.optString(JsonKey.CREATE_DATE);
            topic.setCreateDate(TextUtils.isEmpty(createDate) ? 0 : Long.valueOf(createDate));
            topic.setLevel(topicJson.optInt(JsonKey.LEVEL));
            topic.setUserTitle(topicJson.optString(JsonKey.USERTITLE));
            topic.setLocation(topicJson.optString(JsonKey.LOCATION));
            topic.setMobileSign(topicJson.optString(JsonKey.MOBILESIGN));
            topic.setStatus(topicJson.optInt(JsonKey.STATUS));
            topic.setReplyStatus(topicJson.optInt(JsonKey.REPLY_STATUS));
            topic.setFlag(topicJson.optInt(JsonKey.FLAG));
            topic.setReplyPostsId(topicJson.optInt(JsonKey.REPLY_POSTS_ID));
            topic.setUserAvatar(topicJson.optString(JsonKey.ICON));
            topic.setForumName(jsonObject.optString(JsonKey.FORUMNAME));
            topic.setSourceWebUrl(jsonObject.optString(JsonKey.FORUMTOPICURL));

            Reply reply = new Reply();
            reply.setTopicId(topic.getId());
            reply.setUserId(topic.getUserId());
            reply.setType(topic.getType());
            reply.setName(topic.getUserNickName());
            reply.setId(topic.getReplyPostsId());
            reply.setPosition(1);
            reply.setPostsDate(topic.getCreateDate());
            reply.setAvatar(topic.getUserAvatar());
            reply.setLevel(topic.getLevel());
            reply.setUserTitle(topic.getUserTitle());
            reply.setLocation(topic.getLocation());
            reply.setMobileSign(topic.getMobileSign());
            reply.setReplyStaus(topic.getReplyStatus());
            reply.setStatus(topic.getStatus());
            reply.setRoleNum(1);
            reply.setTitle(topic.getTitle());

            JSONArray contentArray = topicJson.optJSONArray(JsonKey.CONTENT);
            parseReplyContent(contentArray, reply);
            replyList.add(reply);
        }
        parseReply(jsonObject.optJSONArray(JsonKey.LIST), replyList);
        topic.getReplyList().addAll(replyList);
        getAdapter().setHasMore(jsonObject.optInt(JsonKey.HAS_NEXT) != 0);
        return replyList;
    }

    private void parseReply(JSONArray replyArray, List<Reply> replyList) {
        JSONObject replyJson;
        int size = replyArray.length();
        for (int i = 0; i < size; i++) {
            Reply reply = new Reply();
            replyJson = replyArray.optJSONObject(i);
            reply.setUserId(replyJson.optInt(JsonKey.REPLY_ID));
            reply.setTopicId(topic.getId());
            reply.setType(replyJson.optString(JsonKey.REPLY_TYPE));
            reply.setName(replyJson.optString(JsonKey.REPLY_NAME));
            reply.setId(replyJson.optInt(JsonKey.REPLY_POSTS_ID));
            reply.setPosition(replyJson.optInt(JsonKey.POSITION));
            String date = replyJson.optString(JsonKey.POSTS_DATE);
            reply.setPostsDate(TextUtils.isEmpty(date) ? 0 : Long.valueOf(date));
            reply.setAvatar(replyJson.optString(JsonKey.ICON));
            reply.setLevel(replyJson.optInt(JsonKey.LEVEL));
            reply.setUserTitle(replyJson.optString(JsonKey.USERTITLE));
            reply.setLocation(replyJson.optString(JsonKey.LOCATION));
            reply.setMobileSign(replyJson.optString(JsonKey.MOBILESIGN));
            reply.setReplyStaus(replyJson.optInt(JsonKey.REPLY_STATUS));
            reply.setStatus(replyJson.optInt(JsonKey.STATUS));
            reply.setRoleNum(replyJson.optInt(JsonKey.ROLE_NUM));
            reply.setTitle(replyJson.optString(JsonKey.TITLE));
            reply.setQuote(replyJson.optInt(JsonKey.IS_QUOTE) != 0);
            reply.setQuotePid(replyJson.optInt(JsonKey.QUOTE_PID));
            reply.setQuoteContent(replyJson.optString(JsonKey.QUOTE_CONTENT));
            reply.setQuoteUserName(replyJson.optString(JsonKey.QUOTE_USER_NAME));

            JSONArray contentArray = replyJson.optJSONArray(JsonKey.REPLY_CONTENT);
            parseReplyContent(contentArray, reply);

            replyList.add(reply);

        }
    }

    private void parseReplyContent(JSONArray contentArray, Reply reply) {
        JSONObject contentJson;
        int size = contentArray.length() > 2 ? 2 : contentArray.length();
        for (int i = 0; i < size; i++) {
            ReplyContent content = new ReplyContent();
            contentJson = contentArray.optJSONObject(i);
            content.setInfo(contentJson.optString(JsonKey.INFOR));
            content.setType(contentJson.optInt(JsonKey.TYPE));
            content.setUrl(contentJson.optString(JsonKey.URL));
            content.setOriginalInfo(contentJson.optString(JsonKey.ORIGINALINFO));
            content.setAid(contentJson.optInt(JsonKey.AID));
            reply.addContent(content);
        }
        String html = JsonParser.parseReplyContentToHtml(contentArray);
        DBManager.getInstance().insertReplyDetail(reply.getTopicId(), reply.getId(), html);
    }

    @Override
    protected void loadDataFromServer() {

        HttpRequestManager.getInstance(AppContext.getInstance()).
                loadTopicDetail(10, topic.getId(), 0, topic.getForumId(), getPage(),
                        new ListXJsonListener(){
                            @Override
                            public void onResponse(List<Reply> response) {
                                super.onResponse(response);
                                getActivity().invalidateOptionsMenu();
                                setTitle(topic.getForumName());
                            }
                        }, new SimpleErrorListener(), getVolleyTag()
                );

    }

    @Override
    protected void loadDataFromCache() {

    }

    @Override
    public String getVolleyTag() {
        return TopicReplyListlFragment.class.getSimpleName();
    }

    @Override
    public String getCacheKey() {
        return null;
    }

    @Override
    public void handleArgs(Bundle args) {
        if (args != null) {
            topic = (Topic) args.getSerializable(IntentParamsKey.TOPIC);
        }
    }

    @Override
    public void onItemClick(int position, View item) {
        if (getListener() != null) {
            Bundle data = new Bundle();
            data.putInt(IntentParamsKey.ACTION, TopicDetailActivity.ACTION_REPLY_DETAIL);
            data.putInt(IntentParamsKey.CURRENT, position);
            data.putInt(IntentParamsKey.PAGE, getPage());
            getListener().onFragmentInteraction(data);
        }
    }
}
